package com.easy.carl.algorithm.tree;

import com.easy.carl.algorithm.tree.tmp.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName Connect116
 * @Description 116. 填充每个节点的下一个右侧节点指针
 * @Author zheng
 * @Date 2022/1/27 10:12
 * @Version 1.0
 **/
public class Connect116 {
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                if (i!=size-1){
                    node.next=queue.peek();
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return root;
    }
}
